<template>
  <div class="mainBox">
    <table border>
      <thead>
        <td style="width: 10%">序号</td>
        <td style="width: 46%">名称</td>
        <td style="width: 9%">页数</td>
        <td style="width: 15%">创建时间</td>
        <td style="width: 20%">操作</td>
      </thead>
      <tbody>
        <tr v-for="(i, index) in data" :key="i.timestamp">
          <td>
            {{ index + 1 }}
          </td>
          <td>
            <div class="nameTd" v-show="!i.isSave">
              <el-input v-model="i.name" placeholder="可只输入支撑材料名称" />
              <MUpload
                list-type="text"
                :limit="1"
                v-model="i.file"
                class="theupload"
                @change="changeUpload"
                @click="theupLoad(index)"
              />
            </div>
            <div v-if="i.isSave">
              <MTooltipBox
                class="open-link"
                :content="i.name"
                @click="previewFile(i)"
              >
              </MTooltipBox>
            </div>
          </td>
          <td>
            <el-input-number
              v-show="!i.isSave"
              v-model="i.fileSum"
              type="number"
              style="width: 100px"
              :min="1"
              :max="9999999999"
              :precision="0"
              controls-position="right"
            />
            <div v-show="i.isSave">{{ i.fileSum }}</div>
          </td>
          <td>
            {{ $dateFormat(i.time, props.dateFormat) }}
          </td>
          <td>
            <div class="icontd">
              <el-tooltip
                v-if="i.isSave"
                class="box-item"
                effect="dark"
                content="编辑"
                placement="top"
              >
                <el-icon style="color: #2f5aa3" @click="edit(index)"
                  ><EditPen
                /></el-icon>
              </el-tooltip>

              <el-tooltip
                v-else
                class="box-item"
                effect="dark"
                content="保存"
                placement="top"
              >
                <el-icon style="color: #039d12" @click="save(index, i.file, i.name)"
                  ><Select
                /></el-icon>
              </el-tooltip>
              <el-tooltip
                class="box-item"
                effect="dark"
                content="删除"
                placement="top"
              >
                <el-icon style="color: #d9001b" @click="del(index)"
                  ><CloseBold
                /></el-icon>
              </el-tooltip>
              <el-tooltip
                class="box-item"
                effect="dark"
                content="上移"
                placement="top"
              >
                <el-icon style="color: #2f5aa3" @click="toTop(index)"
                  ><ArrowUpBold
                /></el-icon>
              </el-tooltip>
              <el-tooltip
                class="box-item"
                effect="dark"
                content="下移"
                placement="top"
              >
                <el-icon style="color: #2f5aa3" @click="toDown(index)"
                  ><ArrowDownBold
                /></el-icon>
              </el-tooltip>
            </div>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="addbtn" @click="add">
      <span class="plusIcon">
        <span class="vertical"></span>
        <span class="horizontal"></span>
      </span>
      点击添加
    </div>
    <MFileList ref="mfileList" :fileData="fileData" />
  </div>
</template>
<script setup lang="ts">
import {
  Select,
  CloseBold,
  ArrowUpBold,
  ArrowDownBold,
  EditPen
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, watch, toRef } from 'vue'
import { MTooltipBox } from '@/components/table'

defineOptions({
  name: 'MBackingMaterial',
  inheritAttrs: false
})

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  dateFormat: {
    type: String,
    default: 'YYYY-MM-DD HH:mm:ss'
  }
})

const emits = defineEmits(['update:modelValue'])

const data: any = toRef(props, 'modelValue')

const mfileList = ref()
const fileData = ref([])

let theview
console.log('MBackingMaterial=>')
watch(
  () => data,
  (val) => {
    emits('update:modelValue', val.value)

    theview = document.querySelectorAll('.theupload')
    theview.forEach((i: any, index) => {
      i.children[1].addEventListener('click', () => {
        // 上传了文件才能预览
        if (val.value[index].file[0]?.url) {
          fileData.value = val.value[index].file
        } else {
          fileData.value = []
        }

        mfileList.value.detailsVisible = true
      })
    })
  },
  { deep: true }
)
const date = new Date()

function getTime() {
  const date = new Date()
  return `${date.getFullYear()}-${date.getMonth() + 1}-${
    date.getDate() > 9 ? date.getDate() : '0' + date.getDate()
  } ${date.getHours() > 9 ? date.getHours() : '0' + date.getHours()}:${
    date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes()
  }:${date.getSeconds() > 9 ? date.getSeconds() : '0' + date.getSeconds()}`
}

// 新增
function add() {
  data.value.push({
    time: getTime(),
    timestamp: date.getTime(),
    isSave: false,
    file: [],
    fileSum: 1
  })
}

// 重载
const isReload = ref(true)
const reload = () => {
  isReload.value = true
}

// 保存
function save(i: any, file: any, name: string) {
  if(name === '') {
    ElMessage.error('请输入文件名称！')
    return
  }
  if (!(Array.isArray(file) && file.length > 0)) {
    ElMessage.error('请上传文件！')
    return
  }
  ElMessageBox.confirm('确定进行保存操作吗?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      ElMessage({
        type: 'success',
        message: '保存成功'
      })
      data.value[i].isSave = true
    })
    .catch(() => {})
}

// 删除
function del(index: number) {
  data.value.splice(index, 1)
}
// 上移
function toTop(index: number) {
  if (index !== 0) {
    data.value.splice(
      index - 1,
      1,
      ...data.value.splice(index, 1, data.value[index - 1])
    )
  } else {
    ElMessage({
      type: 'warning',
      message: '已经是第一条了'
    })
  }
}
// 下移
function toDown(index: number) {
  if (index !== data.value.length - 1) {
    data.value.splice(
      index + 1,
      1,
      ...data.value.splice(index, 1, data.value[index + 1])
    )
  } else {
    ElMessage({
      type: 'warning',
      message: '已经是最后一条了'
    })
  }
}

// 编辑
function edit(index: number) {
  data.value[index].isSave = false
}

let index = 0

function changeUpload(file: any) {
  setTimeout(() => {
    if (!data.value[index].name && file.length) {
      data.value[index].name = file[0].name
    }
  })
}

function theupLoad(num: number) {
  index = num
}

function previewFile(data: any) {
  fileData.value = data?.file || []
  mfileList.value.detailsVisible = true
}
</script>

<style lang="scss" scoped>
.open-link {
  cursor: pointer;
  // color: #1890ff;
  // text-decoration: underline;
}
.mainBox {
  width: 100%;
  overflow: hidden;
}

table {
  border-collapse: collapse;
  border-color: #cdcdcd;
  width: 100%;
  font-size: 20px;
  thead {
    width: 100%;
    background: #e2ebff;
  }
  tbody {
    width: 100%;
  }
  td {
    text-align: center;
    padding: 10px 20px;
  }
}

.nameTd {
  display: grid;
  grid-template-columns: 1fr 100px;
  gap: 30px;
  :deep(.m-upload) {
    .theupload {
      display: flex;
      flex-direction: row-reverse;
      justify-content: space-around;
      .el-upload {
        div {
          width: 25px;
          height: 25px;
          background: url('@/assets/svg/upLoad.svg') no-repeat center center;
          button {
            display: none;
          }
        }
      }
      ul {
        width: 25px;
        height: 25px;
        background: url('@/assets/svg/view.svg') no-repeat center center;
        position: relative;
        margin: 0;
        cursor: pointer;

        li {
          display: none;
          label {
            display: none;
          }
          a {
            width: 25px;
            height: 25px;
            position: absolute;
            top: 0;
            left: 0;
            cursor: pointer;
            span {
              display: none;
            }
          }
          i {
            display: none;
            svg {
              display: none;
            }
          }
        }
      }
    }
  }
}

.icontd {
  display: flex;
  justify-content: space-around;
  font-weight: bold;
  font-size: 25px;
  i {
    cursor: pointer;
  }
}

.addbtn {
  cursor: pointer;
  border: 1px dashed var(--el-color-primary);
  padding: 10px;
  text-align: center;
  margin-top: 20px;
  font-size: 20px;
}

.plusIcon {
  display: inline-block;
  width: 16px;
  height: 16px;
  background-color: var(--el-color-primary);
  margin-right: 5px;
  border-radius: 2px;
  position: relative;
  .vertical {
    display: inline-block;
    width: 3px;
    height: 10px;
    background-color: #fff;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .horizontal {
    display: inline-block;
    width: 10px;
    height: 3px;
    background-color: #fff;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>
